#!/usr/bin/python

# Raspberry Pi <-> Dual MCP3008 SPI 16adc board 
#
# Requires:
#
#       in /etc/modprobe.d/raspi-blacklist.conf
#           #blacklist spi-bcm2708     <= Must be commented out! Need reboot for changes
#
#       spidev + py-spidev (http://github.com/doceme/py-spidev)
#           git clone http://github.com/doceme/py-spidev
#           cd ./py-spidev
#           python setup.py install
#
# 16 ADC BOARD  <--> RPi GPIO
#   MISO             MISO
#   MOSI             MOSI
#   CLK              SCLK
#   CEO              CE0
#   CE1              CE1
#   3.3V             3.3V
#   GND              GND
#
#   Ax/y  => Analog inputs
#

import sys

try: 
    import RPi.GPIO as GPIO
except RuntimeError:
    print "Error while trying to load GPIO module, try running the script with superuser privileges!"


import spidev                                           # SPI Hardware communication Module
import time

# Display correct syntax and exits
def usage():
    print "Usage: " + __file__ + " <adc> <channel>"
    sys.exit(0)

if __name__ == "__main__":
 
    # User must provide 2 parameters, ADC and CHANNEL numbers
    # ADC must be either 0 or 1
    # Channel must range from 0 to 7
    # ./rpi_16adc.py 1 5 will display the analog input A1/5 (see board)

    error = False 
    if len(sys.argv) != 3 :
	usage()
    else:
	if not sys.argv[1].isdigit() or not sys.argv[2].isdigit():
		usage()
	if int(sys.argv[1]) not in range(2) or int(sys.argv[2]) not in range(8):
		usage()

    adc = int(sys.argv[1])
    channel = int(sys.argv[2])

    spiDevice = spidev.SpiDev()                         # Create a spidev Object
    
    while True:
        spiDevice.open(0,adc)                    	# Open communication with SPI device conected to CEX (/dev/spidev0.X) X  = adc
        values = spiDevice.xfer2([1,(8+channel)<<4,0])  # Sends 3 bytes (required for MCP3008, 128+X=>channel X ), returns a list of 3 bytes as values
        index = ((values[1]&3) << 8) + values[2]        # 10 bit coded value
        print "O" * int(index*20/1023.) + "-" * (20-int(index*20/1023.))
        time.sleep(0.09)
        spiDevice.close()                               # Close device, required to prevent "Too many IO files open" error
    
    
    
